import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:roundcheckbox/roundcheckbox.dart';
import 'package:shenfuhui/entity/user_info_entity.dart';
import 'package:shenfuhui/routers/routers.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../config/config.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../utils/count_down_time_util.dart';

class RegisterPage extends StatefulWidget {
  const RegisterPage({Key? key}) : super(key: key);

  @override
  State<RegisterPage> createState() => _RegisterState();
}

class _RegisterState extends State<RegisterPage> {
  String _userName = "";
  String _passWord = "";
  String _phone = "";
  String _valiCode = "";
  String _shareCode = "";

  bool check = true;

  String codeTips = '获取验证码';
  bool isGetCode = true;

  getCheckBoxBorderColor() {
    if (check) {
      return const Color(0xFF3C78FF);
    } else {
      return const Color(0xFFD1D1D1);
    }
  }

  ///
  /// 登录的逻辑
  ///
  login(Function onSucces) async {
    if (_userName.length < 11) {
      EasyLoading.showToast("请输入正确的手机号");
      return;
    }
    if (_passWord.length < 6) {
      EasyLoading.showToast("请输入6位以上密码");
      return;
    }

    var content = const Utf8Encoder().convert(_passWord);
    String md5pwd = "${md5.convert(content)}";
    dynamic result =
        await Api.login({'username': _userName, 'password': md5pwd});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 200) {
      //成功获得token,并保存起来
      SharedPreferences prefs = await SharedPreferences.getInstance();
      bool isOk = await prefs.setString('token', jsonResult['token']);
      // LogUtil.v(jsonResult['token']);
      if (isOk) {
        dynamic users = await Api.getUserinfo();
        Map<String, dynamic> resultUsers = Map.from(users);
        UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
        // onSucces.call();
        onSucces(infoEntity);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('注册'),
        centerTitle: true,
      ),
      body: Container(
          width: double.infinity,
          color: Config.colorBg,
          height: double.infinity,
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Stack(
              children: [
                // Image.asset(
                //   'assets/images/login_bg.png',
                //   width: double.infinity,
                //   height: 300.w,
                //   fit: BoxFit.fill,
                // ),
                Container(
                  width: double.infinity,
                  padding:
                      EdgeInsets.symmetric(vertical: 38.w, horizontal: 38.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: EdgeInsets.only(left: 40.w, top: 10.w),
                        width: double.infinity,
                        child: Text(
                          Config.appName,
                          style: TextStyle(
                              fontSize: 60.sp, fontWeight: FontWeight.bold),
                        ),
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin:
                            EdgeInsets.only(top: 50.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.phone,
                          textAlign: TextAlign.justify,
                          maxLength: 11,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _phone = value;
                            });
                          },
                          style: TextStyle(
                              fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入手机号',
                            hintStyle:
                                const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            counterText: '',
                            prefixIcon: Icon(
                              Icons.phone_android,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding:
                                EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin:
                            EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _userName = value;
                            });
                          },
                          style: TextStyle(
                              fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入用户名',
                            hintStyle:
                                const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            counterText: '',
                            prefixIcon: Icon(
                              Icons.person,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding:
                                EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin:
                            EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          obscureText: true,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _passWord = value;
                            });
                          },
                          style: TextStyle(
                              fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入登录密码',
                            counterText: '',
                            hintStyle:
                                const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            prefixIcon: Icon(
                              Icons.lock_outline_rounded,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding:
                                EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Stack(
                        children: [
                          Container(
                            height: 88.w,
                            width: double.infinity,
                            margin: EdgeInsets.only(
                                top: 26.w, left: 40.w, right: 40.w),
                            child: TextField(
                              keyboardType: TextInputType.text,
                              textAlign: TextAlign.justify,
                              obscureText: true,
                              maxLength: 6,
                              maxLines: 1,
                              onChanged: (value) {
                                setState(() {
                                  _valiCode = value;
                                });
                              },
                              style: TextStyle(
                                  fontSize: 26.sp, color: Config.colorText1),
                              decoration: InputDecoration(
                                hintText: '请输入验证码',
                                counterText: '',
                                hintStyle:
                                    const TextStyle(color: Config.colorText3),
                                focusedBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(
                                      color: Config.colorDivider),
                                ),
                                enabledBorder: OutlineInputBorder(
                                  borderRadius: BorderRadius.all(
                                    Radius.circular(44.w),
                                  ),
                                  borderSide: const BorderSide(
                                      color: Config.colorDivider),
                                ),
                                fillColor: Config.colorDivider,
                                filled: true,
                                prefixIcon: Icon(
                                  Icons.verified_user_outlined,
                                  color: Config.colorMain,
                                  size: 33.w,
                                ),
                                contentPadding:
                                    EdgeInsets.symmetric(vertical: 10.w),
                              ),
                            ),
                          ),
                          Positioned(
                            right: 60.w,
                            top: 50.w,
                            child: InkWell(
                              onTap: () {
                                if (!isGetCode) {
                                  return;
                                }
                                CountDownTimeUtil(60, 1, (int currentTime) {
                                  var _currentTime = currentTime;
                                  setState(() {
                                    if (_currentTime == 0) {
                                      codeTips = '获取验证码';
                                      isGetCode = true;
                                    } else {
                                      codeTips = '$_currentTime';
                                    }
                                  });
                                });
                                isGetCode = false;
                              },
                              child: Text(
                                codeTips,
                                style: TextStyle(
                                  color: Config.colorMain,
                                  fontSize: 22.sp,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Container(
                        height: 88.w,
                        width: double.infinity,
                        margin:
                            EdgeInsets.only(top: 26.w, left: 40.w, right: 40.w),
                        child: TextField(
                          keyboardType: TextInputType.text,
                          textAlign: TextAlign.justify,
                          obscureText: true,
                          maxLength: 20,
                          maxLines: 1,
                          onChanged: (value) {
                            setState(() {
                              _shareCode = value;
                            });
                          },
                          style: TextStyle(
                              fontSize: 26.sp, color: Config.colorText1),
                          decoration: InputDecoration(
                            hintText: '请输入邀请码',
                            counterText: '',
                            hintStyle:
                                const TextStyle(color: Config.colorText3),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.all(
                                Radius.circular(44.w),
                              ),
                              borderSide:
                                  const BorderSide(color: Config.colorDivider),
                            ),
                            fillColor: Config.colorDivider,
                            filled: true,
                            prefixIcon: Icon(
                              Icons.group_add_outlined,
                              color: Config.colorMain,
                              size: 33.w,
                            ),
                            contentPadding:
                                EdgeInsets.symmetric(vertical: 10.w),
                          ),
                        ),
                      ),
                      Container(
                        width: double.infinity,
                        height: 84.w,
                        margin: EdgeInsets.fromLTRB(40.w, 60.w, 40.w, 0),
                        child: ElevatedButton(
                          clipBehavior: Clip.antiAlias,
                          onPressed: () => login((UserInfoEntity infoEntity) {
                            Provider.of<UserInfoProvider>(context,
                                    listen: false)
                                .changeUserinfo(infoEntity);
                            Routes.router.pop(context);
                          }),
                          style: ElevatedButton.styleFrom(
                              shape: const StadiumBorder()),
                          child: const Text('立即注册'),
                        ),
                      ),
                      Container(
                          margin: EdgeInsets.only(right: 50.w, top: 20.w),
                          width: double.infinity,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              RoundCheckBox(
                                  size: 15,
                                  checkedWidget: const Icon(
                                    Icons.check,
                                    color: Colors.white,
                                    size: 10,
                                  ),
                                  checkedColor: Config.colorMain,
                                  uncheckedColor: Config.colorBg,
                                  border: Border.all(
                                      color: check
                                          ? Config.colorMain
                                          : Config.colorText3,
                                      width: 1),
                                  isChecked: check,
                                  onTap: (selected) {
                                    check = selected!;
                                    setState(() {});
                                  }),
                              Padding(
                                padding: EdgeInsets.all(6.w),
                              ),
                              Text(
                                "同意并接受",
                                style: TextStyle(
                                  color: Config.colorText2,
                                  fontSize: 26.sp,
                                ),
                              ),
                              InkWell(
                                onTap: () {},
                                child: Text(
                                  "《用户注册协议》",
                                  style: TextStyle(
                                    color: Config.colorMain,
                                    fontSize: 26.sp,
                                  ),
                                ),
                              ),
                            ],
                          )),
                    ],
                  ),
                ),
              ],
            ),
          )),
    );
  }
}
